package protocol;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import statter.Stats;

public class CommSckServerOut implements Runnable {
	
	private int port;
	private CommandRelay cmdRly;
	private Thread thread;
	private ServerSocket sSckt;
	private Socket sckt;
	private ObjectOutputStream os;
	private Stats statter;

	public CommSckServerOut(CommandRelay cmdRly, Stats statter) {
		this(11168,cmdRly, statter);
	}

	public CommSckServerOut(int port, CommandRelay cmdRly, Stats statter) {
		this.statter = statter;
		this.statter.addSection("Outgoing tcp thread");
		this.port = port;
		this.cmdRly = cmdRly;
		thread = new Thread(this);
		thread.start();
	}
	

	@Override
	public void run() {
		try {
			sSckt = new ServerSocket(port);
			sckt = sSckt.accept();
			os = new ObjectOutputStream(sckt.getOutputStream());
			while(sckt.isConnected()) {
				statter.statStart("Outgoing tcp thread");
				Cmd cmd = cmdRly.getOutCmd();
				if (cmd != null) {
					os.writeObject(cmd);
				}
				else {
					try {
						Thread.sleep(200);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				statter.statEnd("Outgoing tcp thread");
			}
		} 
		catch (IOException e) {
			e.printStackTrace();
		}
		
	}

}
